$(function() {
    $("#ldBtn").on("click", function() {
        $.ajax({
            url: "http://localhost:3000/users",
            type: "GET",
            dataType: "json"
        }).done(function(response) {
            if (response) {
                var tableOp = tableOperator($("#rsTbl"), response);
                tableOp.createTable();
            }
        });
    });
    
    function tableOperator(table, data) {
        var obj = {};
        obj.createTable = function() {
            table.empty();
            data.forEach((item) => {
                var td1 = $("<td>").text(item.id);
                var td2 = $("<td>").text(item.name);
                var td3 = $("<td>").text(item.age);
                var delBtn = $("<button>").text("Delete").addClass("del").attr("data-id", item.id);
                var td4 = $("<td>").append(delBtn);
                
                var tr = $("<tr>").append(td1).append(td2).append(td3).append(td4);
                table.append(tr);
            });
            this.bindDelEvent();
        }
        
        obj.bindDelEvent = function() {
            $("button.del").on("click", function() {
                var index = $(this).attr("data-id");
                var tr = $(this).parent().parent();
                
                $.ajax({
                    url: "http://localhost:3000/users/" + index,
                    type: "DELETE"
                }).done(function(response) {
                    tr.remove();
                });
            });
        }
        return obj;
    }
});